package com.factory.rest.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.factory.common.bean.Config;
import com.factory.common.bean.User;
import com.factory.common.constant.UserConstant;
import com.factory.common.pojo.Result;
import com.factory.common.utils.StringUtil;
import com.factory.rest.service.AsyncService;
import com.factory.rest.service.ConfigService;
import com.factory.rest.service.UserService;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/rest/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private AsyncService asyncService;

    @Autowired
    private ConfigService configService;

    /**
     * 用户登录接口
     * @param param
     * @return
     */
    @PostMapping(value = "/login")
    public Result login(@RequestBody JSONObject param) {
        log.info("用户登录接口,{}",param);
        if(StringUtil.isEmpty(param.getString("username"))){
            return Result.fail("用户名不能为空");
        }
        if(StringUtil.isEmpty(param.getString("password"))){
            return Result.fail("用户密码不能为空");
        }
        return userService.login(param.getString("username"), param.getString("password"));
    }

    /**
     * 用户退出登录接口
     * @return
     */
    @GetMapping(value = "/loginOut")
    public Result loginOut() {
        log.info("用户退出登录接口");
        return userService.loginOut();
    }

    /**
     * 查询用户的菜单
     * @param conditions
     * @return
     */
    @PostMapping(value = "/queryUserMenus")
    public Result queryUserMenus(@RequestBody Map<String,Object> conditions ) {

        User user = userService.getLoginUser().get();
        if(user == null){
            return Result.fail("请先登录后再访问");
        }

        return Result.success(userService.queryUserMenus(user.getId()),"查询成功!");
    }

    /**
     * 用户注册接口
     *
     * @return
     */
    @PostMapping("/register")
    @ResponseBody
    public Result register(@RequestBody User user) {
        log.info("用户注册,{}", user);

        if (StringUtil.isEmpty(user.getMobile())) {
            return Result.fail(null, "手机号不能为空", 504);
        }else if(StringUtil.isEmpty(user.getAccount())){
            return Result.fail(null, "账号不能为空", 504);
        }else if(StringUtil.isEmpty(user.getPassword())){
            return Result.fail(null, "密码不能为空", 504);
        }

        User user1 = userService.selectOne(new QueryWrapper<User>().eq("account",user.getAccount()));
        if (null != user1) {
            return Result.fail(null, "用户名已被使用", 504);
        }

        user.setId(StringUtil.getUUID());
        user.setCreateDate(new Date());
        user.setStatus(UserConstant.Status.NORMAL);
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));

        return Result.success(userService.insert(user), "注册成功");
    }

    /**
     * 用户获取验证码接口
     * mobile 手机号
     *
     * @return
     */
    @PostMapping("/code")
    @ResponseBody
    public Result code(@RequestBody Map<String, String> params) {
        log.info("用户获取验证码接口,{}", params);

        if (StringUtil.isEmpty(params.get("mobile"))) {
            return Result.fail(null, "手机号不能为空", 504);
        }

        String code = String.valueOf(new Random().nextInt(9999));
        asyncService.sendCode(params.get("mobile"), code);

        return Result.success(code, "发送成功");
    }

    /**
     * 用户重置密码
     * mobile 手机号
     *
     * @return
     */
    @PostMapping("/resetPassword")
    @ResponseBody
    public Result resetPassword(@RequestBody User user) {
        log.info("用户重置密码接口,{}", user);

        if (StringUtil.isEmpty(user.getAccount())) {
            return Result.fail(null, "用户名不能为空", 504);
        }
        if (StringUtil.isEmpty(user.getPassword())) {
            return Result.fail(null, "密码不能为空", 504);
        }

        User user1 = userService.selectOne(new QueryWrapper<User>().eq("account",user.getAccount()));
        if (null == user1) {
            return Result.fail(null, "用户不存在!", 504);
        }

        user1.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        userService.updateById(user1);

        return Result.success(null, "修改成功");
    }

    /**
     * 用户修改配置
     * @param config
     * @return
     */
    @PostMapping("/setConfig")
    public Result setConfig(@RequestBody Config config){
        if(StringUtil.isEmpty(config.getCkey())){
            return Result.fail("key不能为空!");
        }else if(StringUtil.isEmpty(config.getCvalue())){
            return Result.fail("value不能为空!");
        }else if(StringUtil.isEmpty(config.getName())){
            return Result.fail("name不能为空!");
        }

        User user = userService.getLoginUser().get();
        Config currentConfig = configService.selectOne(new QueryWrapper<Config>().eq("user_id", user.getId()).eq("ckey", config.getCkey()));
        if(null == currentConfig){
            currentConfig = new Config();
            currentConfig.setId(StringUtil.getUUID());
            currentConfig.setCreateDate(new Date());
            currentConfig.setStatus(1);
            currentConfig.setUserId(user.getId());
            currentConfig.setCkey(config.getCkey());
            currentConfig.setName(config.getName());
            currentConfig.setCvalue(config.getCvalue());

            configService.insert(currentConfig);
        }else {
            currentConfig.setName(config.getName());
            currentConfig.setCvalue(config.getCvalue());
            configService.updateById(currentConfig);
        }

        return Result.success(currentConfig,"修改成功");
    }

    /**
     * 用户查询配置列表
     * @param param
     * @return
     */
    @PostMapping("/configList")
    public Result configList(@RequestBody Map<String, Object> param){
        log.info("用户查询配置列表,{}",param);
        QueryWrapper<Config> configQueryWrapper = new QueryWrapper<>();

        User user = userService.getLoginUser().get();
        configQueryWrapper.eq("user_id",user.getId());

        if(StringUtil.notEmpty(param.get("ckey"))){
            configQueryWrapper.eq("ckey",param.get("ckey"));
        }

        return Result.success(configService.selectList(configQueryWrapper));
    }
}
